package com.ruoyi.wechat.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.wechat.domain.MsgTemplate;
import com.ruoyi.wechat.mapper.MsgTemplateMapper;
import com.ruoyi.wechat.service.MsgTemplateService;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.template.WxMpTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * @author yan
 * @date  2022-07-18
 */
@Slf4j
@Service("msgTemplateService")
public class MsgTemplateServiceImpl extends ServiceImpl<MsgTemplateMapper, MsgTemplate> implements MsgTemplateService {
    @Resource
    private WxMpService wxService;
    @Resource
    private MsgTemplateMapper msgTemplateMapper;

    @Override
    public MsgTemplate selectByName(String name) {
        Assert.hasText(name, "模板名称不得为空");
        return this.getOne(new QueryWrapper<MsgTemplate>()
                .eq("name", name)
                .eq("status", 1)
                .last("LIMIT 1"));
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void syncWxTemplate(String appid) throws WxErrorException {
        Map<String, Object> map = new HashMap<>();
        map.put("appid", appid);
        msgTemplateMapper.deleteByMap(map);
        List<WxMpTemplate> wxMpTemplateList = wxService.getTemplateMsgService().getAllPrivateTemplate();
        log.info("模板同步：{}", wxMpTemplateList);
        List<MsgTemplate> templates = wxMpTemplateList.stream().filter(wxMpTemplate -> !"订阅模板消息".equals(wxMpTemplate.getTitle())).map(item -> new MsgTemplate(item, appid)).collect(Collectors.toList());
        log.info("模板同步2：{}", templates);
        this.saveOrUpdateBatch(templates);
    }

}
